<template>
	<view class="fix-top-window">
		<view class="uni-header">
			<uni-ad-admin-breadcrumb />
		</view>
		<view class="uni-container">
			<uni-ad-admin-panel :items="panelData"></uni-ad-admin-panel>

			<view class="uni-ad-admin--x flex p-1015">
				<view class="uni-ad-admin-card-header">
					最近30天收益分析
				</view>
				<view class="uni-charts-box">
					<qiun-data-charts type="area" :chartData="chartData" :eopts="eopts" echartsH5 echartsApp
						tooltipFormat="tooltipCustom" :errorMessage="errorMessage" />
				</view>
			</view>

			<view class="uni-ad-admin--x flex p-1015">
				<view class="uni-ad-admin-card-header">
					昨日收益应用
				</view>
			</view>
			<unicloud-db ref="udb" :collection="tableName+','+appTableName" field="appid,revenue,name" :where="where"
				page-data="replace" orderby="revenue desc" :getcount="true" :page-size="options.pageSize"
				:page-current="options.pageCurrent" v-slot:default="{data,pagination,loading,error,options}"
				:options="options" loadtime="manual" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || loading ? '请求中...' : '没有更多数据'"
					border stripe type="" style="min-height: 600px;">
					<uni-tr>
						<uni-th align="center">#</uni-th>
						<uni-th align="center">AppID</uni-th>
						<uni-th align="center">应用名称</uni-th>
						<uni-th align="center">预估收益</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{ parseInt((index+1) + (pagination.current-1) * pagination.size) }}
						</uni-td>
						<uni-td align="center">{{item.appid[0] ? item.appid[0].appid : ''}}</uni-td>
						<uni-td align="center">{{item.appid[0] ? item.appid[0].name : ''}}</uni-td>
						<uni-td align="center">
							{{ (item.revenue / 1000).toFixed(2) }} 元
						</uni-td>
						<uni-td align="center">
							<button type="primary" v-if="item.appid[0] && item.appid[0].appid" size="mini"
								@click="showDetail(item)">查看收益</button>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>

		</view>

		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		fieldsMap,
		summaryMap
	} from './fieldsMap.js'

	import timeUtil from '@/uni_modules/uni-ad-admin/js_sdk/timeUtil'
	import {
		eopts,
		format
	} from '@/uni_modules/uni-ad-admin/js_sdk/util'
	// 分页配置
	const pageSize = 15
	const pageCurrent = 1
	const db = uniCloud.database()
	const dbCmd = db.command
	const $ = dbCmd.aggregate
	const ADREGION = 1
	export default {
		data() {
			return {
				fieldsMap,
				tableName: 'uni-ad-app-revenues',
				appTableName: 'opendb-app-list',
				where: {
					ad_region: ADREGION,
					revenue_date: timeUtil.yestoday()
				},
				options: {
					pageSize,
					pageCurrent,
				},
				panelData: summaryMap,
				chartData: {},
				errorMessage: "",
				eopts,
				loading: false
			}
		},
		created() {
			this.getSummaryData()
			this.getChartData()
		},
		onReady() {
			this.getTableData()
		},
		methods: {
			onPageChanged(e) {
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			showDetail(row) {
				let appid = row.appid[0] ? row.appid[0].appid : ''
				if (appid == '') {
					uni.showToast({
						title: 'appid 无效',
						icon: 'none'
					})
					return
				}

				uni.navigateTo({
					url: '../detail/detail?appid=' + appid
				})
			},
			valFormat(mapper, item) {
				let val = item[mapper.field] !== undefined ? item[mapper.field] : '-'
				if (mapper.formatter) {
					return format(val / 1000, mapper.formatter)
				}

				return val
			},
			async getMonthRevenue(start) {
				return await db.collection(this.tableName)
					.where({
						ad_region: ADREGION,
						revenue_date: dbCmd.gte(start)
					})
					.groupBy('revenue_date')
					.groupField('sum(revenue) as revenue')
					.orderBy('revenue_date desc')
					.get()
			},
			async getSummaryData() {
				let yestodaySummary = 0,
					sevenSummary = 0,
					monthSummary = 0,
					lastMonthSummary = 0

				let yestoday = timeUtil.yestoday()
				let weekday = timeUtil.plusDay(-7)
				let first = timeUtil.getMonthStart()
				let last_month_end = timeUtil.plusDay(-1, 'yyyyMMdd', first)
				let last_month_start = timeUtil.getMonthStart(timeUtil.toTime(last_month_end))
				let dates = [
					[yestoday, yestoday],
					[weekday, yestoday],
					[first, yestoday],
					[last_month_start, last_month_end]
				]

				for (let i in dates) {
					let where = {
						ad_region: ADREGION,
						revenue_date: dbCmd.and(
							dbCmd.gte(dates[i][0]),
							dbCmd.lte(dates[i][1])
						)
					}
					
					let revenues = await db.collection(this.tableName)
						.aggregate()
						.match(where)
						.group({
							_id: null,
							revenue: $.sum('$revenue')
						})
						.end()
						
					let {
						data
					} = revenues.result
					
					let revenue = data.length > 0 ? data[0].revenue || 0 : 0
					this.panelData[i].value = format(revenue / 1000)
				}
			},
			async getChartData() {
				let name = '预估收益'
				const options = {
					categories: [],
					series: [{
						name,
						label:{
							show:false
						},
						data: []
					}]
				}
				let month = timeUtil.plusDay(-31)
				let yestoday = timeUtil.yestoday()

				let res = await this.getMonthRevenue(month)
				let result = res.result.data

				let start = timeUtil.toTime(month)
				let end = timeUtil.toTime(yestoday)
				for (let i = start; i <= end; i += 86400000) {
					let cd = timeUtil.timeFormat(i, 'yyyyMMdd')

					options.categories.push(timeUtil.dateFormat(cd))
					
					let find = result.find((item) => {
						return item.revenue_date == cd;
					})
					
					let revenue = find ? find.revenue : 0
					options.series[0].data.push((revenue / 1000).toFixed(2))
				}

				this.chartData = options
			},
			getTableData() {
				this.$refs.udb.loadData()
			}
		}
	}
</script>

<style lang="scss">
	@import "@/uni_modules/uni-ad-admin/common/uni-ad-admin.scss";
</style>